package com.work.user.service.impl;

import com.work.user.dao.MenuMapper;
import com.work.user.dao.RoleMapper;
import com.work.user.pojo.Menu;
import com.work.user.pojo.Role;
import com.work.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    //查询全部
    @Override
    public List<Role> findAll() {
        List<Role> roles = roleMapper.selectAll();
        /*for (Role role : roles) {
            Set<Menu> menus = menuMapper.findByRoleId(role.getId());
            role.setMenus(menus);
        }*/
        return roles;
    }

    //添加角色
    @Override
    public void add(Role role, Integer[] mids) {
        roleMapper.add(role);
        Integer rid = role.getId();
        //添加到中间表
        this.setRoleAndPermission(rid, mids);
    }

    //修改角色
    @Override
    public void update(Role role, Integer[] mids) {
        roleMapper.updateByPrimaryKey(role);
        Integer rid = role.getId();
        //删除中间表
        roleMapper.deleteAssocication(rid);
        //重新添加关系表
        this.setRoleAndPermission(rid, mids);
    }

    //删除角色
    @Override
    public void delete(Integer id) {
        if (id == 1 || id == 5) {
            throw new RuntimeException("超级用户角色不允许删除！");
        }
        //先删除中间表
        roleMapper.deleteAssocication(id);
        //再删除角色
        roleMapper.deleteByPrimaryKey(id);
    }

    //根据id查询
    @Override
    public Role findById(Integer id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        Integer rid = role.getId();
        Set<Menu> menus = menuMapper.findByRoleId(rid);
        role.setMenus(menus);
        return role;
    }

    //添加角色与权限一对多关系到中间表
    public void setRoleAndPermission(Integer rid, Integer[] mids) {
        if (mids != null && mids.length > 0) {
            for (Integer mid : mids) {
                Map<String, Integer> map = new HashMap<>();
                map.put("rid", rid);
                map.put("mid", mid);
                roleMapper.setRoleAndMenu(map);
            }
        }
    }

}
